package com.dhcc.file.controller;


import com.dhcc.file.model.Attach;
import com.dhcc.file.service.FileService;
import com.dhcc.utils.CommonUtils;
import com.dhcc.utils.FileUtils;
import com.dhcc.utils.ReturnResponse;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletRequest;
import java.io.*;
import java.util.*;

/**
 * 文件上传接口
 *
 * @author
 * @date
 */
@RestController
@Slf4j
public class FileController {

    @Value("${file.dir}")
    String fileDir;

    @Autowired
    FileUtils fileUtils;

    final String REDIS_FILE_PREVIEW_PDF_KEY = "converted-preview-pdf-file";

    @Autowired
    private FileService fileService;

    @Autowired
    private RedisTemplate redisTemplate;

    @RequestMapping(value = "fileUpload", method = RequestMethod.POST)
    public String fileUpload(@RequestParam("file") MultipartFile file,
                             HttpServletRequest request) throws JsonProcessingException {
        String fileName = file.getOriginalFilename();
        log.info("fileName:{}", fileName);
        int lastIndexOf = fileName.lastIndexOf(".") + 1;
        String suffix = fileName.substring(lastIndexOf);
        String demoDir = CommonUtils.getNowTimeTillDay() + "/" + CommonUtils.getNowTime();

        String demoPath = demoDir + "/";
        //随机生成的文件名称
        String uuid = CommonUtils.getUUID();
        String fileNames = uuid + "." + suffix;
        Attach attach = new Attach();
        attach.setId(uuid);
        attach.setFileName(demoPath + fileNames);
        attach.setFilePath(fileDir);
        attach.setSuffix(suffix);
        attach.setCreateTime(CommonUtils.getNowTimeDetail());
        attach.setName(fileName);
        log.info("文件存储对象attach：{}", attach.toString());
        int count = fileService.add(attach);
        if (count < 1) {
            return new ObjectMapper().writeValueAsString(new ReturnResponse<String>(1, "FAILURE", "上传文件异常"));
        }
        //创建文件目录
        File outFile = new File(fileDir + demoPath);
        if (!outFile.exists()) {
            outFile.mkdirs();
        }
        try (InputStream in = file.getInputStream();
             OutputStream ot = new FileOutputStream(fileDir + demoPath + fileNames)) {
            byte[] buffer = new byte[1024];
            int len;
            while ((-1 != (len = in.read(buffer)))) {
                ot.write(buffer, 0, len);
            }
            return new ObjectMapper().writeValueAsString(new ReturnResponse<String>(0, "SUCCESS", null));
        } catch (IOException e) {
            e.printStackTrace();
            return new ObjectMapper().writeValueAsString(new ReturnResponse<String>(1, "FAILURE", null));
        }
    }

    @RequestMapping(value = "deleteFile", method = RequestMethod.GET)
    public String deleteFile(String id) throws JsonProcessingException {
        Attach attach = fileService.getById(id);
        String filePath = attach.getFilePath();
        String fileName = attach.getFileName();
        File file = new File(filePath + fileName);
        if (file.exists()) {
            file.delete();
        }
        File filePreview = new File(filePath);
        if (filePreview.exists()) {
            File[] files = filePreview.listFiles();
            if (files != null && files.length > 0) {
                for (File file1 : files) {
                    String name = file1.getName();
                    if (name.contains(id)) {
                        file1.delete();
                    }
                }
            }
        }
        Object o = redisTemplate.opsForValue().get(REDIS_FILE_PREVIEW_PDF_KEY);
        if (o != null) {
            Map<String, String> convertedList = (Map<String, String>) o;
            Set<String> keySet = convertedList.keySet();
            Iterator<String> iterator = keySet.iterator();
            if (iterator.hasNext()) {
                String key = iterator.next();
                if (key.contains(id)) {
                    convertedList.remove(key);
                }
            }
        }
        fileService.del(id);
        return new ObjectMapper().writeValueAsString(new ReturnResponse<String>(0, "SUCCESS", null));
    }

    @RequestMapping(value = "listFiles", method = RequestMethod.GET)
    public String getFiles() throws JsonProcessingException {
        List<Attach> list = fileService.list();
        return new ObjectMapper().writeValueAsString(list);
    }

    private String getFileName(String name) {
        String suffix = name.substring(name.lastIndexOf("."));
        String nameNoSuffix = name.substring(0, name.lastIndexOf("."));
        String uuid = UUID.randomUUID().toString();
        return uuid + "-" + nameNoSuffix + suffix;
    }


}
